package com.ciwong.epaper.modules.me.ui;

import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.cordva.BaseHtmlActicity;
import com.ciwong.epaper.modules.cordva.SubmitEvent;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.PayHelper;
import com.ciwong.eventbus.EventBus;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.GoBackListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.widget.CWDialog;
import com.ciwong.mobilepay.bean.PayDetail;
import com.ciwong.mobilepay.ui.EMainActivity;

import org.apache.cordova.engine.SystemWebView;
import org.json.JSONObject;

import java.io.File;

/**
 * 报名系统入口
 * Created by lzr on 2016/10/19.
 */
public class RegistrationActivity extends BaseHtmlActicity  {

    public static final int REQUEST_PAY_CODE=100;

    //业务相关
    private int themeId;

    @Override
    protected void preCreate() {
        super.preCreate();
        themeId=getIntent().getIntExtra(IntentFlag.INTENT_FLAG_TYPE,1);
    }

    @Override
    protected void init() {
        super.init();
        setGoBackListener(this);
        setRightBtnListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                MeJumpManager.jumpToRegistRecodH5(R.string.go_back,themeId,RegistrationActivity.this);
            }
        });
        webView.setBackFace(new SystemWebView.BackFace() {
            @Override
            public boolean isGoBack() {
                if(cordovaWebView==null||webView==null){
                    finish();
                }
                String endStr=cordovaWebView.getUrl().substring(cordovaWebView.getUrl().indexOf("?"),cordovaWebView.getUrl().length());
                String temp="?themeId="+themeId+"#!/form";
                if(endStr.equals(temp)){

                    CWDialog dialog=new CWDialog(RegistrationActivity.this).setMessage("是否退出报名页面?").setNegativeButton("取消", null).setPositiveButton("退出", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            webView.goBackNew();
                            dialog.dismiss();
                        }
                    });
                    dialog.show();
                    return false;
                }
                return true;
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    @Override
    protected void loadData() {
        super.loadData();
        setStartURL("file://" + ESystem.getRegistPath() + File.separator + "signUp.html?themeId="+themeId);
        Log.d("xixin","singUp------load----"+"file://" + ESystem.getRegistPath() + File.separator + "signUp.html?themeId="+themeId);
        cordovaWebView.loadUrl(startURL.toString());
    }

    @Override
    public void goBack() {
        super.goBack();
        try {
            String endStr=cordovaWebView.getUrl().substring(cordovaWebView.getUrl().indexOf("?"),cordovaWebView.getUrl().length());
            if(endStr.equals("?themeId="+themeId+"#!/")){
                finish();
            }else{
                cordovaWebView.backHistory();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * eventBus 回调方法
     * @param submitEvent
     */
    public void onEventMainThread(SubmitEvent submitEvent) {
        Log.d("xixin","----eventBus----");
        final  String id = submitEvent.getId();
        try {
            if ("SetTitle".equals(id)) {
                if (null != submitEvent.getJson()) {
                    JSONObject jsonObject = new JSONObject(submitEvent.getJson());
                    String title = jsonObject.getString("title");
                    setTitleText(title);
                    String endStr=cordovaWebView.getUrl().substring(cordovaWebView.getUrl().indexOf("?"),cordovaWebView.getUrl().length());
                    if(endStr.equals("?themeId="+themeId+"#!/")){
                        setRightBtnText("参赛记录");
                    }else{
                        hideRightBtn();
                    }

                }
            }else if("CallToPay".equals(id)){
                if (null != submitEvent.getJson()) {
                    Log.d(TAG,"----CallToPay-------"+submitEvent.getJson());
                    UserInfoBase userInfo = getUserInfoBase();
                    JSONObject  tempJson= new JSONObject(submitEvent.getJson());
                    JSONObject jsonObject=new JSONObject(tempJson.getString("data"));
                    double fee=jsonObject.getDouble("fee");
                    String Buymsg;
                    if(jsonObject.has("buyMsg")){
                        Buymsg=jsonObject.getString("buyMsg");
                    }else {
                        Buymsg=null;
                    }
                    if(fee<=0){
                        showToastSuccess("报名成功");
                        MeJumpManager.jumpToRegistRecodH5(R.string.go_back,themeId,RegistrationActivity.this);
                        loadData();
                    }else{
                        Log.d(TAG,"----CallToPayyyyyyy-------"+submitEvent.getJson());
                        PayDetail payDetail = PayHelper.getInstance().getPayDetail(userInfo.getUserId(), userInfo.getRealName(),jsonObject.getString("matchTitle"), "",
                                jsonObject.getDouble("fee"), jsonObject.getString("goodsName"), 1, 2,jsonObject.getString("notifyAddress") ,
                                jsonObject.getString("orderNo"),"", "9", "1", "999",
                                "("+jsonObject.getString("stage")+")",
                                "比赛赛区："+jsonObject.getString("area")+"   比赛时长："+jsonObject.getString("duration")+"分钟","",Buymsg);
                        MeJumpManager.jumpToRegistRecodH5(R.string.go_back,themeId,RegistrationActivity.this);
                        MeJumpManager.jumpToPay(R.string.go_back,payDetail,this,REQUEST_PAY_CODE);
                        loadData();
                    }
                }
            }else if("ref".equals(id)){
                loadData();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        if (resultCode == RESULT_OK && data != null) {
            switch (requestCode) {
                case REQUEST_PAY_CODE:
                    Log.d("xixin","--------返回---------"+requestCode);
                    int payResult = data.getIntExtra(EMainActivity.PAY_RESULT, 0);
                    // 支付购买成功
                    if (payResult == EMainActivity.PAY_RESULT_SUCCES) {
                        showToastSuccess("报名成功");
                        loadData();
                    } else {
                        showToastError("报名失败");
                        loadData();
                    }
                    break;
                default:
                    break;
            }
        }
        hideMiddleProgressBar();
    }


}
